﻿using System;
using System.Collections.Generic;
using System.IO;
using CommandLineParser.Exceptions;
using ZenWplExporter.Wpl;

namespace ZenWplExporter
{
	/// <summary>
	/// The Program
	/// </summary>
	internal class Program
	{
		/// <summary>
		/// Main entry point
		/// </summary>
		/// <param name="args">The args.</param>
		private static int Main(string[] args)
		{
			var argParser = new ArgumentParser<Arguments>();

			try
			{
				// Parse Command-Line Arguments
				argParser.ParseCommandLine(args);

				// Load WPL
				string wplName = argParser.Values.WplPath.Name;
				Logger.WriteInfo("Reading WPL playlist [{0}]", wplName);
				Playlist wplList = Playlist.Load(argParser.Values.WplPath.FullName);

				// Build a list of source file names with full path
				Logger.WriteInfo("Validating WPL playlist", wplName);
				List<string> sourceFiles = GetSourceFileNames(argParser.Values.WplPath.FullName, wplList);

				// Build ZEN playlist
				Logger.WriteInfo("Building ZEN playlist");
				var builder = new ZenPlayListBuilder();
				ZenPlayList zenList = builder.Build(sourceFiles, argParser.Values.ZenMusicDir.FullName, argParser.Values.Organize);

				// Save ZEN Playlist
				Logger.WriteInfo("Saving ZEN playlist");
				string m3uName = Path.GetFileNameWithoutExtension(wplName) + ".m3u";
				zenList.Save(Path.Combine(argParser.Values.ZenPlaylistDir.FullName, m3uName), argParser.Values.Overwrite);

				return 0;
			}
			catch (MandatoryArgumentNotSetException)
			{
				argParser.ShowUsage();
				return 1;
			}
			catch (Exception ex)
			{
				Logger.WriteError(ex);
				return 1;
			}
		}

		private static List<string> GetSourceFileNames(string wplPath, Playlist wplList)
		{
			string wplDir = Path.GetDirectoryName(wplPath);
			var sourceFiles = new List<string>(wplList.Body.Sequence.Count);
			foreach (var media in wplList.Body.Sequence)
			{
				if (Path.IsPathRooted(media.Source))
				{
					sourceFiles.Add(media.Source);
				}
				else
				{
					sourceFiles.Add(Path.GetFullPath(Path.Combine(wplDir, media.Source)));
				}
			}
			return sourceFiles;
		}
	}
}